package coasttocoast.client.swing;

import coasttocoast.client.controllers.GameController;
import coasttocoast.client.swing.controls.GamePanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Logger;

/**
 * @author gsh
 */
public class CoastToCoast {
  private static Logger logger = Logger.getLogger(CoastToCoast.class.getName());

  private static JFrame mainWindow;

  private static void createAndShowGui() {
    mainWindow = new JFrame("Coast To Coast");
    mainWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    mainWindow.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        if (GameController.get().canExit()) {
          mainWindow.dispose();
        }
      }
    });
    mainWindow.getContentPane().add(new GamePanel());
    mainWindow.setJMenuBar(createMenuBar());
    mainWindow.pack();

    // Center the new window on the desktop
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();
    int x = (screenSize.width - mainWindow.getWidth()) / 2;
    int y = (screenSize.height - mainWindow.getHeight()) / 2;
    mainWindow.setLocation(x, y);

    mainWindow.setVisible(true);
  }

  private static JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    menuBar.add(fileMenu);

    JMenuItem saveItem = new JMenuItem("Save", KeyEvent.VK_S);
    saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
    saveItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        GameController.get().saveGame();
      }
    });
    fileMenu.add(saveItem);

    fileMenu.addSeparator();
    
    JMenuItem exitItem = new JMenuItem("Exit", KeyEvent.VK_X);
    exitItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        mainWindow.setVisible(false);
        mainWindow.dispose();
      }
    });
    fileMenu.add(exitItem);

    return menuBar;
  }

  public static void main(String... args) {
    logger.entering(CoastToCoast.class.getName(), "main");
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGui();
        GameController.get().fireStart();
      }
    });
    logger.exiting(CoastToCoast.class.getName(), "main");
  }
}
